import * as bcrypt from 'bcryptjs';
import { AuthProvider, getUserByUsername, getUserByEmail } from '../../../services/uctoo/uctoo_user';
import log from '../../../helpers/logger';
import { pushDiscordWebhook } from '../../../helpers/pushDiscordWebhook';
import { authorizeAndEnd } from '../../../helpers/authorizeAndEnd';
import { defaultRouteHandler } from '../../../../interfaces';
import db from '../../../lib/db';

//Function for handling user signin using local strategy (email, password)
const handleSignin: defaultRouteHandler = async (req, res) => {
  try {
    const body = await req.json();
    const { username, password, verifyCode } = body;
    //查询config表是否开启了验证码配置
    const EnableVerifyCode = await db.config.findFirst({
      where: {
        key: 'EnableVerifyCode',
      },
    });

    if(EnableVerifyCode.value === '1'){
      if (!verifyCode) {
        return res.status(400).json({ errno: "42001", errmsg: "verify code is required" });
      }else{
        const nowTimestamp = Date.now();
        const date = new Date(nowTimestamp);
        const withTimezone = date.toISOString();
        //10分钟之内的验证码
        const tenMinutesAgo = new Date(nowTimestamp - 10 * 60 * 1000).toISOString();
        //sms_log表查询created_at时间十分钟之内的验证码是否存在
        const verifyCodeRecord = await db.sms_log.findFirst({
          where: {
            created_at: {
              gte: tenMinutesAgo,
            },
            code: verifyCode,
            event: 'verify',
          }})
        //如果验证码存在，删除验证码记录
        if (verifyCodeRecord) {
          await db.sms_log.delete({
            where: {
              id: verifyCodeRecord.id,
            },
          });
        }
                //如果验证码不存在，返回错误信息
        if (!verifyCodeRecord) {
          return res.status(400).json({ errno: "42002", errmsg: "verify code is invalid" });
        }
      }
    }
    

    const user = await getUserByUsername(username);
    if (!user) return res.status(404).json({ errno: "40401", errmsg: "user not found" });

    const passwordMatch = await bcrypt.compare(password, user.password);
   
    await bcrypt.hash(password, 10).then((hash) => {
      //console.log(hash);
    });
    if (!passwordMatch) return res.status(400).json({ errno: "42007", errmsg: "login failed, username/password not match" });

    return authorizeAndEnd(user, req, res, AuthProvider.Local, true);
  } catch (e) {
    log.error(e);
    res
      .status(500)
      .json({ errno: "50000", errmsg: e.message || 'Internal server error' });
  }
};
export default handleSignin;
